#include "bird.h"

#include "util/jni_util.h"
#include "util/log_util.h"

namespace bird {

// long nativeCreate(String name);
jlong nativeCreate(JNIEnv *env, jobject thiz, jstring name) {
  const char *name_chars = env->GetStringUTFChars(name, NULL);

  Bird *bird = new Bird(std::string(name_chars));

  env->ReleaseStringUTFChars(name, name_chars);
  return reinterpret_cast<jlong>(bird);
}

// void nativeDestroy(long nativeRef);
void nativeDestroy(JNIEnv *env, jobject thiz, jlong ref) {
  Bird *bird = reinterpret_cast<Bird *>(ref);
  delete bird;
}

// String nativeGreeting(long nativeRef);
jstring nativeGreeting(JNIEnv *env, jobject thiz, jlong ref) {
  Bird *bird = reinterpret_cast<Bird *>(ref);
  return env->NewStringUTF(bird->greeting().c_str());
}

}  // namespace bird

// register natives

CJNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *jvm, void */*reserved*/) {
  JNIEnv *env = nullptr;
  if (jvm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
    LOGW("JNI_OnLoad GetEnv error");
    return JNI_ERR;
  }

  static JNINativeMethod methods[] = {
    {"nativeCreate", "(Ljava/lang/String;)J", reinterpret_cast<void*>(bird::nativeCreate)},
    {"nativeDestroy", "(J)V", reinterpret_cast<void*>(bird::nativeDestroy)},
    {"nativeGreeting", "(J)Ljava/lang/String;", reinterpret_cast<void*>(bird::nativeGreeting)},
  };
  registerNatives(env, "cc/eevee/jni/libdynamic/Bird", methods,
      sizeof(methods) / sizeof(methods[0]));

  return JNI_VERSION_1_6;
}

CJNIEXPORT void JNICALL JNI_OnUnload(JavaVM */*jvm*/, void */*reserved*/) {
}
